﻿using CommomDetec;
using HikVisionTool.DAL;
using HikVisionTool.Helper;
using HikVisionTool.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 网络机高清测试.BLL
{
    class HikDataBLL
    {
        private HikVisonDAL hikVisonDAL = new HikVisonDAL();
        private MainWindow _window;
        public HikDataBLL(MainWindow mainWindow)
        {
            _window = mainWindow;
        }
        public void PostHikDate(DetectionResult entity, string wknum, string pk)
        {
            try
            {
                string ScanOkUrl = "http://192.168.2.2:8771/api/ShopFloor/PostScanOkData";
                string HikCheckUrl = "http://192.168.2.2:8771/api/ShopFloor/PostHikCheckData";
                DateTime time = DateTime.Now;
                // 测试站点提交OK记录
                string ScanOkStr = ScanOkData(entity, wknum, pk,time);
                // 站点提交检测明细记录
                string HikCheckStr = HikCheckData(entity, wknum, pk,time);
                if (HttpHelper.PostJsonData(HikCheckUrl, HikCheckStr) == false)
                {
                    FileHelper.WriteJson(HikCheckStr, "采集数据\\" + pk, "check");
                }
                if (HttpHelper.PostJsonData(ScanOkUrl, ScanOkStr) == false)
                {
                    FileHelper.WriteJson(ScanOkStr, "采集数据\\" + pk, "scan");
                }
                // 修改条码主机状态 未判断结果 
                ChangeBarcodeStaus(entity, wknum,time);
            }
            catch (Exception ex)
            {
                FileHelper.WriteLog(ex.ToString());
            }
        }

        public string ScanOkData(DetectionResult entity, string wknum, string pk,DateTime time)
        {
            // 测试站点提交OK记录

            var obj = new CheckDataModel.ScanOk
            {
                pk_id = pk,
                lifnr = _window.lifnr, // 供应商编号，固定值
                wknum = wknum,
                barcd = entity.Serial,
                pline = "MX" + _window.pline,
                processid = _window.processid,
                funct = getFunct(entity.Result),
                wkposition = _window.wkposition,
                barcd_batch = "",
                shift = time.Hour > 19 ? "1" : "0",
                crname = _window.userModel.username,
                crtime = time,
                update_flag = "I",
                status = 0,
            };
            string post_dat = JsonConvert.SerializeObject(obj);
            return post_dat;
        }

        public string getFunct(ResultStatus result)
        {
            if (ResultStatus.SUCCESS.Equals(result))
            {
                return "S1";
            }
            return "S4";
        }
        public void ChangeBarcodeStaus(DetectionResult entity, string wknum,DateTime time)
        {
            try
            {
                string url = "http://192.168.2.2:8771/api/ShopFloor/ChangeBarcodeStaus";
                string newPline = "MX" + _window.pline;
                string funct = getFunct(entity.Result);
                string next_processid = "";
                Sql3Helper.t_HK_workorder_barcode_status obj = null;
                if (_window.wkposition == "THT通用测试" || _window.wkposition == "THT加密升级")
                {
                    next_processid = "703";
                }
                if (_window.wkposition == "高清测试")
                {
                    string mes_url = "http://192.168.2.2:8080/default/com.mx.mes.stock.inspection.insertInspection.searchnextprocess.biz.ext";
                    MesProdLineModel dto = new MesProdLineModel
                    {
                        matsn = entity.Serial,
                        mocode = wknum
                    };
                    string next_pline = HttpHelper.HttpPostData(mes_url, JsonConvert.SerializeObject(dto));
                    if (!next_pline.Contains("null"))
                    {
                        MesProdLineResult rt = JsonConvert.DeserializeObject<MesProdLineResult>(next_pline);
                        next_processid = rt.nextprocess;
                    }
                }
                if (next_processid == "")
                {
                    return;
                }
                obj = new Sql3Helper.t_HK_workorder_barcode_status
                {
                    barcd = entity.Serial,
                    wknum = wknum,
                    next_pline = newPline,
                    next_processid = next_processid,
                    processid = _window.processid,
                    arrivetime = time,
                    chname = _window.userModel.username,
                    chtime = time,
                    status = 0
                };
                hikVisonDAL.ChangStatus(obj);
            }
            catch (Exception ex)
            {
                FileHelper.WriteLog(ex.ToString());
                return;
            }
        }

        public string HikCheckData(DetectionResult entity, string wknum, string pk,DateTime time)
        {
            string url = "http://192.168.2.2:8771/api/ShopFloor/PostHikCheckData";

            //string pk = $"{lifnr}{entity.Serial}{DateTime.Now.ToString("yyyyMMddHHMMssfff")}";
            string funct = getFunct(entity.Result);

            var obj = new CheckDataModel.HikCheck
            {
                pk_id = pk,
                lifnr = _window.lifnr,
                wknum = wknum,
                barcd = entity.Serial,
                pline = "MX" + _window.pline,
                processid = _window.processid,
                funct = funct,
                wkposition = _window.wkposition,
                ck_start_dt = entity.StartTime,
                ck_end_dt = entity.EndTime,
                crname = _window.userModel.username,
                crtime = time,
                update_flag = "I",
                status = 0
            };

            List<CheckDataModel.FirstDetail> DetailFirst = new List<CheckDataModel.FirstDetail>();
            List<CheckDataModel.SecondDetail> DetailSecond = new List<CheckDataModel.SecondDetail>();

            List<CheckSubItem> subItems = entity.CheckSubItems;
            foreach (var subItem in subItems)
            {
                CheckDataModel.FirstDetail first = new CheckDataModel.FirstDetail();
                first.pk_id = pk;
                first.lifnr = _window.lifnr;
                first.seqfid = int.Parse(subItem.ID);
                first.ck_item_name = subItem.Name;
                first.ck_item_desc = subItem.Description;
                first.funct = getFunct(subItem.Result);
                first.ck_start_dt = subItem.StartTime;
                first.ck_end_dt = subItem.EndTime;
                first.crname = _window.userModel.username;
                first.crtime = time;
                first.update_flag = "I";
                first.status = 0;

                DetailFirst.Add(first);

                List<Item> items = subItem.Items;
                for (int i = 0; i < items.Count; i++)
                {
                    Item item = items[i];
                    CheckDataModel.SecondDetail second = new CheckDataModel.SecondDetail
                    {
                        pk_id = pk,
                        lifnr = _window.lifnr,
                        seqfid = int.Parse(subItem.ID),
                        seqsid = i + 1,
                        ck_item_type = item.Type,
                        ck_item_name = item.Name,
                        ck_item_desc = item.Description,
                        funct = getFunct(item.Result),
                        ck_start_dt = subItem.StartTime,
                        ck_end_dt = subItem.EndTime,
                        crname = _window.userModel.username,
                        crtime = time,
                        update_flag = "I",
                        status = 0
                    };
                    DetailSecond.Add(second);
                }
            }

            obj.DetailFirst = DetailFirst;
            obj.DetailSecond = DetailSecond;
            string post_dat = JsonConvert.SerializeObject(obj);
            return post_dat;
        }

        public void UpOfflineData()
        {

            string path = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.LastIndexOf('\\')) + "\\离线数据";
            string dataPath = path + "\\采集数据";
            string crossPath = path + "\\过站数据";
            if (Directory.Exists(dataPath))
            {
                string[] dataFiles = Directory.GetDirectories(dataPath);
                string ScanOkUrl = "http://192.168.2.2:8771/api/ShopFloor/PostScanOkData";
                string HikCheckUrl = "http://192.168.2.2:8771/api/ShopFloor/PostHikCheckData";
                foreach (var direc in dataFiles)
                {
                    string[] files = Directory.GetFiles(direc);
                    foreach (var file in files)
                    {
                        if (file.Contains("check.txt"))
                        {
                            // 站点提交检测明细记录
                            string HikCheckStr = File.ReadAllText(file);
                            if (HttpHelper.PostJsonData(HikCheckUrl, HikCheckStr) == false)
                            {
                                continue;
                            }
                            Thread.Sleep(100);
                            File.Delete(file);
                        }
                        if (file.Contains("scan.txt"))
                        {
                            // 测试站点提交OK记录
                            string ScanOkStr = File.ReadAllText(file);
                            if (HttpHelper.PostJsonData(ScanOkUrl, ScanOkStr) == false)
                            {
                                continue;
                            }
                            Thread.Sleep(100);
                            File.Delete(file);
                        }
                    }
                    Thread.Sleep(100);
                    try
                    {
                        Directory.Delete(direc);
                    }
                    catch (Exception)
                    {
                    }

                }
            }
        }
    }
}
